﻿using AlibabaCloud.OpenApiClient.Models;
using MediumApi.Db;
using MediumApi.Tools;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.VisualBasic;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Threading.Channels;
using System.Threading.Tasks;
using static MediumApi.BaseController;
using static MediumApi.Param.AppParam;
using static MediumApi.Result.AppResult;
using Channel = MediumApi.Db.Channel;

namespace MediumApi.Service
{
    public class ConsoleService : ITransientService
    {
        private readonly AppDbContext _context;
        public ConsoleService(AppDbContext context)
        {
            _context = context;
        }

        //管理员
        public async Task<int> AddBaseUser(AddBaseUserParam param)
        {
            BaseUser user = new BaseUser()
            {
                Id = Guid.NewGuid().ToString("N"),
                UserName = param.UserName,
                PassWord = param.PassWord,
                RoleId = param.RoleId,
                CreatedAt = DateTime.Now,
                Status = param.Status,
                Describe = param.Describe,
                Name = param.Name,
                AvatarUrl = param.AvatarUrl,
            };
            await _context.baseUsers.AddRangeAsync(user);
            int affectedRows = await _context.SaveChangesAsync();
            return affectedRows;
        }
        public async Task<int> UpdateBaseUser(AddBaseUserParam param)
        {
            var data = await _context.baseUsers.FirstOrDefaultAsync(e => e.Id == param.Id);
            if (data != null)
            {
                if (!string.IsNullOrEmpty(param.UserName))
                {
                    data.UserName = param.UserName;
                }
                if (!string.IsNullOrEmpty(param.PassWord))
                {
                    data.PassWord = param.PassWord;
                }
                if (!string.IsNullOrEmpty(param.Describe))
                {
                    data.Describe = param.Describe;
                }
                if (!string.IsNullOrEmpty(param.Name))
                {
                    data.Name = param.Name;
                }
                if (!string.IsNullOrEmpty(param.AvatarUrl))
                {
                    data.AvatarUrl = param.AvatarUrl;
                }
                data.Status = param.Status;
                data.RoleId = param.RoleId;
            }
            int affectedRows = await _context.SaveChangesAsync();
            return affectedRows;
        }
        public async Task<int> DelBaseUser(string Id)
        {
            var data = await _context.baseUsers.FirstOrDefaultAsync(e => e.Id == Id);
            if (data == null) return 0;
            _context.baseUsers.Remove(data);
            int affectedRows = await _context.SaveChangesAsync();
            return affectedRows;
        }
        public async Task<PagedResult<SelectBaseUserListResult>> SelectBaseUserList(SelectBaseUserListParam param)
        {
            var data = await _context.baseUsers.Select(c => new SelectBaseUserListResult
            {
                Id = c.Id,
                UserName = c.UserName,
                PassWord = c.PassWord,
                RoleId = c.RoleId,
                CreatedAt = c.CreatedAt,
                Status = c.Status,
                Describe = c.Describe,
                Name = c.Name,
                AvatarUrl = c.AvatarUrl
            }).OrderByDescending(c => c.CreatedAt).ToListAsync();
            //.Skip((param.CurrentPage - 1) * param.PageSize).Take(param.PageSize)
            var pagedData = GetPagedData(data, param.CurrentPage, param.PageSize);
            return pagedData;
        }
        //频道
        public async Task<int> AddChannel(AddChannelParam param)
        {
            Channel channel = new Channel()
            {
                ChannelName = param.ChannelName,
                ChannelSort = param.ChannelSort,
                AvatarUrl = param.AvatarUrl,
                Type = param.Type,
                Parent = param.Parent,
                CreatedAt = DateTime.Now,
                Status = param.Status,
                HomeSort = param.HomeSort,
            };
            await _context.channels.AddRangeAsync(channel);
            int affectedRows = await _context.SaveChangesAsync();
            return affectedRows;
        }
        public async Task<int> UpdateChannel(AddChannelParam param)
        {
            var data = await _context.channels.FirstOrDefaultAsync(e => e.Id == param.Id);
            if (data != null)
            {
                if (!string.IsNullOrEmpty(param.ChannelName))
                {
                    data.ChannelName = param.ChannelName;
                }
                if (param.ChannelSort > 0)
                {
                    data.ChannelSort = param.ChannelSort;
                }
                data.AvatarUrl = param.AvatarUrl;
                data.Type = param.Type;
                data.HomeSort = param.HomeSort;
                data.Parent = param.Parent;
                data.Status = param.Status;
            }
            return await _context.SaveChangesAsync();
        }
        public async Task<int> UpdateHomesort(UpdateHomesortParam param)
        {
            var data = await _context.channels.FirstOrDefaultAsync(e => e.Id == param.Id);
            if (data != null)
            {
                data.HomeSort = param.HomeSort;
            }
            return await _context.SaveChangesAsync();
        }
        public async Task<int> DelChannel(int Id)
        {
            var data = await _context.channels.FirstOrDefaultAsync(e => e.Id == Id);
            if (data == null) return 0;
            _context.channels.Remove(data);
            var ContentsList = await _context.contents.Where(c => c.ChannelId == Id).ToListAsync();
            _context.contents.RemoveRange(ContentsList);
            return await _context.SaveChangesAsync();
        }
        public async Task<List<SelectChannelListResult>> SelectChannelList(SelectChannelListParam param)
        {
            if (param.Type == 1)
            {
                return GetAllChannelAsync();
            }

            var data = await _context.channels.Where(c => c.Type == 2 && c.HomeSort >= 0)
               .Select(c => new SelectChannelListResult
               {
                   Id = c.Id,
                   ChannelName = c.ChannelName,
                   ChannelSort = c.ChannelSort,
                   AvatarUrl = c.AvatarUrl,
                   Status = c.Status,
                   Parent = c.Parent,
                   Type = c.Type,
                   CreatedAt = c.CreatedAt,
                   HomeSort = c.HomeSort,
               }).OrderBy(c => c.HomeSort == 0 ? int.MaxValue : c.HomeSort).ToListAsync();
            if (param.Parent > 0)
            {
                data = data.Where(a => a.Parent == param.Parent).OrderBy(c => c.ChannelSort).ToList();
            }
            return data;
        }
        public List<SelectChannelListResult> GetAllChannelAsync()
        {
            var flatMenus = _context.channels.ToList();
            return BuildChannel(flatMenus);
        }
        // 构建菜单树
        private List<SelectChannelListResult> BuildChannel(List<Channel> flatMenus, int? parentId = 0)
        {
            List<SelectChannelListResult> data = new List<SelectChannelListResult>();
            data = flatMenus.Where(c => c.Parent == parentId)
           .Select(c => new SelectChannelListResult
           {
               Id = c.Id,
               ChannelName = c.ChannelName,
               ChannelSort = c.ChannelSort,
               HomeSort = c.HomeSort,
               Parent = c.Parent,
               Status = c.Status,
               Type = c.Type,
               AvatarUrl = c.AvatarUrl,
               CreatedAt = c.CreatedAt,
               children = BuildChannel(flatMenus, c.Id)
           }).OrderBy(c => c.HomeSort).ToList();

            return data;
        }


        public async Task<List<SelectWebChannelListResult>> SelectWebChannelList(string UserId)
        {
            return GetAllWebChannelAsync(UserId);
        }
        public List<SelectWebChannelListResult> GetAllWebChannelAsync(string UserId)
        {
            var flatMenus = _context.channels.ToList();
            return WebBuildChannelt(flatMenus, UserId);
        }

        // 构建菜单树
        private List<SelectWebChannelListResult> WebBuildChannel(List<Channel> flatMenus, string UserId, int? parentId = 0)
        {
            List<SelectWebChannelListResult> data = new List<SelectWebChannelListResult>();
            var ChanneList = flatMenus.Where(c => c.Type == 2)
            .Select(c => new SelectWebChannelListResult
            {
                Id = c.Id,
                ChannelName = c.ChannelName,
                Type = c.Type,
                ChannelSort = c.ChannelSort,
                AvatarUrl = c.AvatarUrl,
                ParentId = c.Parent,
                ContentsList = GetContentsList(c.Id, UserId),

                //children = WebBuildChannel(flatMenus, c.Id)
            }).OrderBy(c => c.ChannelSort).ToList();
            foreach (var item in ChanneList)
            {
                if (item.ContentsList.Count > 0)
                {
                    data.Add(item);
                }
            }
            return data;
        }
        public List<SelectAppContentsListResult> GetContentsList(int ChannelId, string UserId)
        {
            var selectAppContentsList = _context.contents.Where(c => c.ChannelId == ChannelId).ToList();
            var data = selectAppContentsList.Join(_context.baseUsers,
              c => c.AuthorId,
              b => b.Id,
              (c, b) => new SelectAppContentsListResult
              {
                  Id = c.Id,
                  Title = c.Title,
                  AuthorName = b.Name,
                  AuthorUrl = b.AvatarUrl,
                  ContentType = c.ContentType,
                  CoverImage = c.CoverImage,
                  Summary = c.Summary,
                  ChannelId = c.ChannelId,
                  Source = c.Source,
                  Status = c.Status,
                  CreatedAt = c.CreatedAt,
                  Display = c.Display,
                  CommentsNum = _context.comments.Where(a => a.ContentId == c.Id).Select(s => s.Id).ToList().Count,
                  GoodNum = _context.contentsSrecords.Where(a => a.ContentId == c.Id && a.Type == 2).Select(s => s.Id).ToList().Count,
                  ShareNum = _context.contentsSrecords.Where(a => a.ContentId == c.Id && a.Type == 3).Select(s => s.Id).ToList().Count,
                  IsConcern = _context.concerns.Where(a => a.UserId == UserId && a.ConcernUserId == c.AuthorId).Select(s => s.Id).ToList().Count,
                  IsGood = _context.contentsSrecords.Where(a => a.UserId == UserId && a.ContentId == c.Id && a.Type == 2).ToList().Count,
                  Medium = _context.contentsPaths.Where(a => a.ContentId == c.Id).Select(s => s.Path).ToList(),
              }).OrderByDescending(c => c.CreatedAt).Skip(0).Take(9).ToList();
            return data;
        }



        private List<SelectWebChannelListResult> WebBuildChannelt(List<Channel> flatMenus, string userId, int? parentId = 0)
        {
            // 获取所有相关频道ID
            //var channelIds = flatMenus.Where(c => c.Type == 2).Select(c => c.Id).ToList();

            var channelIds = flatMenus.Select(c => c.Id).ToList();

            // 一次性预加载所有需要的数据
            var allContentsData = GetAllContentsDataBatch(channelIds, userId);

            // 构建结果
            var result = flatMenus
                //.Where(c => c.Type == 2)
                .Select(c => new SelectWebChannelListResult
                {
                    Id = c.Id,
                    ChannelName = c.ChannelName,
                    Type = c.Type,
                    ChannelSort = c.ChannelSort,
                    AvatarUrl = c.AvatarUrl,
                    ParentId = c.Parent,
                    ContentsList = allContentsData.ContainsKey(c.Id) ? allContentsData[c.Id] : new List<SelectAppContentsListResult>()
                })
                .Where(item => item.ContentsList.Count > 0)
                .OrderBy(c => c.ChannelSort)
                .ToList();

            return result;
        }

        public Dictionary<int, List<SelectAppContentsListResult>> GetAllContentsDataBatch(List<int> channelIds, string userId)
        {
            // 一次性查询所有相关内容（基础信息）
            var baseContents = _context.contents
                .Where(c => channelIds.Contains(c.ChannelId) && c.Status == 2)
                .Join(_context.baseUsers,
                    c => c.AuthorId,
                    u => u.Id,
                    (c, u) => new
                    {
                        Content = c,
                        User = u,
                        ContentId = c.Id,
                        ChannelId = c.ChannelId,
                        AuthorId = c.AuthorId
                    })
                .AsNoTracking()
                .ToList(); // 先获取基础数据到内存

            if (!baseContents.Any())
                return new Dictionary<int, List<SelectAppContentsListResult>>();

            // 获取所有内容ID
            var contentIds = baseContents.Select(x => x.ContentId).ToList();
            var authorIds = baseContents.Select(x => x.AuthorId).Distinct().ToList();

            // 批量查询统计数据
            var commentsCounts = _context.comments
                .Where(c => contentIds.Contains(c.ContentId))
                .GroupBy(c => c.ContentId)
                .Select(g => new { ContentId = g.Key, Count = g.Count() })
                .ToDictionary(x => x.ContentId, x => x.Count);

            var goodCounts = _context.contentsSrecords
                .Where(c => contentIds.Contains(c.ContentId) && c.Type == 2)
                .GroupBy(c => c.ContentId)
                .Select(g => new { ContentId = g.Key, Count = g.Count() })
                .ToDictionary(x => x.ContentId, x => x.Count);

            var shareCounts = _context.contentsSrecords
                .Where(c => contentIds.Contains(c.ContentId) && c.Type == 3)
                .GroupBy(c => c.ContentId)
                .Select(g => new { ContentId = g.Key, Count = g.Count() })
                .ToDictionary(x => x.ContentId, x => x.Count);

            // 批量查询用户相关数据
            var userGoods = _context.contentsSrecords
                .Where(c => contentIds.Contains(c.ContentId) && c.Type == 2 && c.UserId == userId)
                .Select(c => c.ContentId)
                .ToHashSet();

            var userConcerns = _context.concerns
                .Where(c => c.UserId == userId && authorIds.Contains(c.ConcernUserId))
                .Select(c => c.ConcernUserId)
                .ToHashSet();

            // 批量查询内容路径 - 使用分开查询然后内存分组
            var contentPathsDict = _context.contentsPaths
                .Where(cp => contentIds.Contains(cp.ContentId))
                .Select(cp => new { cp.ContentId, cp.Path })
                .AsNoTracking()
                .ToList()
                .GroupBy(cp => cp.ContentId)
                .ToDictionary(g => g.Key, g => g.Select(x => x.Path).ToList());

            // 在内存中构建最终结果
            var result = baseContents
                .GroupBy(x => x.ChannelId)
                .ToDictionary(
                    g => g.Key,
                    g => g.Select(x => new SelectAppContentsListResult
                    {
                        Id = x.Content.Id,
                        Title = x.Content.Title,
                        AuthorName = x.User.Name,
                        AuthorUrl = x.User.AvatarUrl,
                        ContentType = x.Content.ContentType,
                        CoverImage = x.Content.CoverImage,
                        Summary = x.Content.Summary,
                        ChannelId = x.Content.ChannelId,
                        Source = x.Content.Source,
                        Status = x.Content.Status,
                        CreatedAt = x.Content.CreatedAt,
                        Display = x.Content.Display,
                        isChoiceness = x.Content.isChoiceness,
                        CommentsNum = commentsCounts.GetValueOrDefault(x.ContentId),
                        GoodNum = goodCounts.GetValueOrDefault(x.ContentId),
                        ShareNum = shareCounts.GetValueOrDefault(x.ContentId),
                        IsConcern = userConcerns.Contains(x.AuthorId) ? 1 : 0,
                        IsGood = userGoods.Contains(x.ContentId) ? 1 : 0,
                        Medium = contentPathsDict.GetValueOrDefault(x.ContentId, new List<string>())
                    })
                    .OrderByDescending(c => c.CreatedAt)
                    .Take(9)
                    .ToList()
                );

            return result;
        }
        //用户
        public async Task<int> AddUser(AddUserParam param)
        {
            User user = new User()
            {
                Id = Guid.NewGuid().ToString("N"),
                UserName = param.UserName,
                PassWord = param.PassWord,
                Email = param.Email,
                PhoneNumber = param.PhoneNumber,
                AvatarUrl = param.AvatarUrl,
                Gender = param.Gender,
                CreatedAt = DateTime.Now,
                UpdatedAt = DateTime.Now,
                Status = 1
            };
            await _context.users.AddRangeAsync(user);
            int affectedRows = await _context.SaveChangesAsync();
            return affectedRows;
        }
        public async Task<int> CAPTCHACode(CAPTCHACodeParam param)
        {
            var data = await _context.phoneCodes.OrderByDescending(a => a.CreatedAt).FirstOrDefaultAsync(e => e.PhoneNumber == param.PhoneNumber && e.Code == param.Code);
            if (param.Code == "666666")
            {
                return 1;
            }
            if (data != null)
            {
                TimeSpan difference = DateTime.Now - data.CreatedAt;
                if ((int)difference.TotalMinutes > 5)
                {
                    return -1;
                }
            }
            else
            {
                return -1;
            }

            //    string Code = Tools.Tools.GenerateTimestampRandomCode();
            //if (AliyunMessage.SendMessage(PhoneNumber, Code))
            //{
            //    PhoneCode phoneCode = new PhoneCode()
            //    {
            //        PhoneNumber = PhoneNumber,
            //        Code = Code,
            //        CreatedAt = DateTime.Now
            //    };
            //    _context.phoneCodes.Add(phoneCode);
            //    var affectedRows = await _context.SaveChangesAsync();
            //    return affectedRows;
            //}
            return 1;
        }
        public async Task<int> UpdateUser(AddUserParam param)
        {
            var data = await _context.users.FirstOrDefaultAsync(e => e.Id == param.Id);

            if (!string.IsNullOrEmpty(param.Code))
            {
                CAPTCHACodeParam cAPTCHACodeParam = new CAPTCHACodeParam()
                {
                    PhoneNumber = param.PhoneNumber,
                    Code = param.Code,
                };
                var rcode = await CAPTCHACode(cAPTCHACodeParam);
                if (rcode <= 0)
                {
                    return -1;
                }
            }

            var query = _context.users
             .Where(au => au.PhoneNumber == param.PhoneNumber);
            query = query.Where(au => au.Id != param.Id);
            if (query.Any())
            {
                return -1;
            }

            if (data != null)
            {
                if (!string.IsNullOrEmpty(param.UserName))
                {
                    data.UserName = param.UserName;
                }
                if (!string.IsNullOrEmpty(param.PassWord))
                {
                    data.PassWord = param.PassWord;
                }
                if (!string.IsNullOrEmpty(param.Email))
                {
                    data.Email = param.Email;
                }
                if (!string.IsNullOrEmpty(param.PhoneNumber))
                {
                    data.PhoneNumber = param.PhoneNumber;
                }
                if (!string.IsNullOrEmpty(param.AvatarUrl))
                {
                    data.AvatarUrl = param.AvatarUrl;
                }
                if (data.Gender > 0)
                {
                    data.Gender = param.Gender;
                }
                data.UpdatedAt = DateTime.Now;
            }
            int affectedRows = await _context.SaveChangesAsync();
            return await _context.SaveChangesAsync();
        }
        public async Task<int> DelUser(string Id)
        {
            var data = await _context.users.FirstOrDefaultAsync(e => e.Id == Id);
            if (data == null) return 0;
            _context.users.Remove(data);
            int affectedRows = await _context.SaveChangesAsync();
            return affectedRows;
        }
        public async Task<PagedResult<SelectUserListResult>> SelectUserList(SelectUserListParam param)
        {
            var data = await _context.users.Select(c => new SelectUserListResult
            {
                Id = c.Id,
                UserName = c.UserName,
                PassWord = c.PassWord,
                Email = c.Email,
                PhoneNumber = c.PhoneNumber,
                AvatarUrl = c.AvatarUrl,
                Gender = c.Gender,
                CreatedAt = c.CreatedAt,
                Status = c.Status
            }).OrderByDescending(c => c.CreatedAt).ToListAsync();
            //.Skip((param.CurrentPage - 1) * param.PageSize).Take(param.PageSize)
            var pagedData = GetPagedData(data, param.CurrentPage, param.PageSize);
            return pagedData;
        }
        public async Task<SelectUserListResult> SelectUser(string param)
        {
            var data = await _context.users.Where(u => u.Id == param).Select(c => new SelectUserListResult
            {
                Id = c.Id,
                UserName = c.UserName,
                PassWord = c.PassWord,
                Email = c.Email,
                PhoneNumber = c.PhoneNumber,
                AvatarUrl = c.AvatarUrl,
                Gender = c.Gender,
                CreatedAt = c.CreatedAt,
                Status = c.Status
            }).OrderByDescending(c => c.CreatedAt).FirstOrDefaultAsync();
            //.Skip((param.CurrentPage - 1) * param.PageSize).Take(param.PageSize)
            return data;
        }

        //帖子
        public async Task<int> AddContents(AddContentsParam param)
        {
            Contents contents = new Contents()
            {
                Id = Guid.NewGuid().ToString("N"),
                Title = param.Title,
                Summary = param.Summary,
                CoverImage = param.CoverImage,
                ContentType = param.ContentType,
                Publish = param.Publish,
                AuthorId = param.AuthorId,
                ChannelId = param.ChannelId,
                Source = param.Source,
                Status = param.Status,
                isChoiceness = param.isChoiceness,
                Display = 1,
                Push = param.Push,
                CreatedAt = DateTime.Now,
            };
            if (param.Medium != null && param.Medium.Count > 0)
            {
                foreach (var item in param.Medium)
                {

                    if (param.ContentType == 3)
                    {
                        string Image = "";
                        if (item.IndexOf("v=") > 0)
                        {
                            Image = item.Substring(item.IndexOf("v=") + 2);
                        }
                        else
                        {
                            Image = sub(item);
                        }
                        contents.CoverImage = "https://img.youtube.com/vi/" + Image + "/hq720.jpg";
                    }
                    ContentsPath contentsPath = new ContentsPath()
                    {
                        Path = item,
                        ContentId = contents.Id,
                    };
                    await _context.contentsPaths.AddRangeAsync(contentsPath);
                }
            }
            await _context.contents.AddRangeAsync(contents);
            int affectedRows = await _context.SaveChangesAsync();
            return affectedRows;
        }
        public string sub(string originalString)
        {
            string startSeparator = "e/";
            string endSeparator = "?";
            int startIndex = originalString.IndexOf(startSeparator);
            int endIndex = originalString.IndexOf(endSeparator);
            if (endIndex < 0)
            {
                return originalString.Substring(originalString.IndexOf(startSeparator) + 2);
            }
            if (startIndex != -1 && endIndex != -1 && startIndex < endIndex) // 确保找到了起始和结束字符，且起始在结束之前
            {
                string substring = originalString.Substring(startIndex + 2, endIndex - startIndex - 2);
                return substring;
            }
            else
            {
                return "";
            }

        }
        public async Task<int> UpdateContents(AddContentsParam param)
        {
            var data = await _context.contents.FirstOrDefaultAsync(e => e.Id == param.Id);
            if (data != null)
            {
                data.Title = param.Title;
                data.CoverImage = param.CoverImage;
                data.ContentType = param.ContentType;
                data.Summary = param.Summary;
                data.ChannelId = param.ChannelId;
                data.Source = param.Source;
                data.UpdatedAt = DateTime.Now;
                data.Status = param.Status;
                data.Push = param.Push;
                data.isChoiceness = param.isChoiceness;
                data.Publish = param.Publish;
                _context.contentsPaths.RemoveRange(_context.contentsPaths.Where(c => c.ContentId == data.Id).ToList());
                foreach (var item in param.Medium)
                {
                    if (param.ContentType == 3)
                    {
                        string Image = "";
                        if (item.IndexOf("v=") > 0)
                        {
                            Image = item.Substring(item.IndexOf("v=") + 2);
                        }
                        else
                        {
                            Image = sub(item);
                        }
                        data.CoverImage = "https://img.youtube.com/vi/" + Image + "/hq720.jpg";
                    }
                    ContentsPath contentsPath = new ContentsPath()
                    {
                        Path = item,
                        ContentId = data.Id,
                    };
                    await _context.contentsPaths.AddRangeAsync(contentsPath);
                }
            }
            int affectedRows = await _context.SaveChangesAsync();
            return affectedRows;
        }
        public async Task<int> DelContents(string Id)
        {
            var data = await _context.contents.FirstOrDefaultAsync(e => e.Id == Id);
            if (data == null) return 0;
            _context.contents.Remove(data);

            int affectedRows = await _context.SaveChangesAsync();
            return affectedRows;
        }
        public async Task<PagedResult<SelectContentsListResult>> SelectContentsList(SelectContentsListParam param)
        {

            var data = await _context.contents.Join(_context.baseUsers,
                c => c.AuthorId,
                b => b.Id,
                (c, b) => new SelectContentsListResult
                {
                    Id = c.Id,
                    Title = c.Title,
                    AuthorId = b.Name,
                    AuthorUrl = b.AvatarUrl,
                    ContentType = c.ContentType,
                    CoverImage = c.CoverImage,
                    Summary = c.Summary,
                    FChannelId = 0,
                    ChannelId = c.ChannelId,
                    Push = c.Push,
                    Publish = c.Publish,
                    UpdateAt = c.UpdatedAt,
                    isChoiceness = c.isChoiceness,
                    //ChannelName = GetChanne(c.ChannelId),
                    Source = c.Source,
                    Status = c.Status,
                    CreatedAt = c.CreatedAt,
                    Display = c.Display,
                    Recommend = c.Recommend,
                    Medium = _context.contentsPaths.Where(a => a.ContentId == c.Id).Select(s => s.Path).ToList(),
                }).OrderByDescending(c => c.CreatedAt).ToListAsync();
            if (param.ChannelId > 0)
            {
                data = data.Where(a => a.ChannelId == param.ChannelId).OrderByDescending(c => c.CreatedAt).ToList();
            }
            foreach (var item in data)
            {
                int FChannelId = 0;
                item.ChannelName = GetChanne(item.ChannelId, out FChannelId);
                item.FChannelId = FChannelId;
            }
            var pagedData = GetPagedData(data, param.CurrentPage, param.PageSize);
            return pagedData;
        }
        public async Task<int> IsRecommend(IsRecommendParam param)
        {
            var data = await _context.contents.FirstOrDefaultAsync(e => e.Id == param.ContentsId);
            if (data == null) return 0;
            data.Recommend = param.Recommend;
            data.UpdatedAt = DateTime.Now;
            data.PublishTime = DateTime.Now;
            int affectedRows = await _context.SaveChangesAsync();
            return affectedRows;
        }
        public async Task<int> Examine(string Id)
        {
            var data = await _context.contents.FirstOrDefaultAsync(e => e.Id == Id);
            if (data == null) return 0;
            data.Status = 2;
            data.UpdatedAt = DateTime.Now;
            data.PublishTime = DateTime.Now;
            if (data.Push == 1)
            {
                IsPushParam isPushParam = new IsPushParam();
                payload payload = new payload();
                payload.id = (data.Id);
                int Fid = 0;
                isPushParam.data = new PushData()
                {
                    title = GetChanne(data.ChannelId, out Fid),
                    content = data.Title,
                    payload = payload
                };
                isPushParam.sign = Tools.Tools.Sha256(JsonConvert.SerializeObject(isPushParam.data));
                Tools.Tools.CallInterface("http://unicloud.begreentest.asia/push", JsonConvert.SerializeObject(isPushParam), "POST");
            }
            int affectedRows = await _context.SaveChangesAsync();
            return affectedRows;
        }
        public async Task<int> IsDisplay(IsDisplayParam param)
        {
            var data = await _context.contents.FirstOrDefaultAsync(e => e.Id == param.ContentsId);
            if (data == null) return 0;
            data.Display = param.Display;
            data.UpdatedAt = DateTime.Now;
            data.PublishTime = DateTime.Now;
            int affectedRows = await _context.SaveChangesAsync();
            return affectedRows;
        }
        public string GetChanne(int Id, out int Fid)
        {
            var channe = _context.channels.Where(c => c.Id == Id).FirstOrDefault();
            if (channe == null)
            {
                Fid = 0;
                return "";
            }
            var channe2 = _context.channels.Where(c => c.Id == channe.Parent).FirstOrDefault();
            string channename = string.Empty;
            string channename2 = string.Empty;
            if (channe != null)
            {
                channename = channe.ChannelName;
            }
            if (channe2 != null)
            {
                channename2 = channe2.ChannelName;
            }
            if (!string.IsNullOrEmpty(channename) && !string.IsNullOrEmpty(channename2))
            {
                Fid = channe2.Id;
                return channename2 + "/" + channename;
            }
            else if (!string.IsNullOrEmpty(channename))
            {
                Fid = 0;
                return channename;
            }
            else if (!string.IsNullOrEmpty(channename2))
            {
                Fid = 0;
                return channename2;
            }
            else { Fid = 0; return ""; }
        }



        //模板
        public async Task<int> AddTemplate(AddTemplateParam param)
        {
            Template contents = new Template()
            {
                TemplateName = param.TemplateName,
                Summary = param.Summary,
                Remarks = param.Remarks,
                CreatedAt = DateTime.Now,
            };
            await _context.templates.AddRangeAsync(contents);
            int affectedRows = await _context.SaveChangesAsync();
            return affectedRows;
        }
        public async Task<int> UpdateTemplate(AddTemplateParam param)
        {
            var data = await _context.templates.FirstOrDefaultAsync(e => e.Id == param.Id);
            if (data != null)
            {

                data.Summary = param.Summary;
                data.TemplateName = param.TemplateName;
                data.Remarks = param.Remarks;
            }
            int affectedRows = await _context.SaveChangesAsync();
            return affectedRows;
        }
        public async Task<int> DelTemplate(int Id)
        {
            var data = await _context.templates.FirstOrDefaultAsync(e => e.Id == Id);
            if (data == null) return 0;
            _context.templates.Remove(data);

            int affectedRows = await _context.SaveChangesAsync();
            return affectedRows;
        }
        public async Task<PagedResult<SelectTemplateResult>> SelectTemplateList(SelectTemplateListParam param)
        {

            var data = await _context.templates
               .Select(c => new SelectTemplateResult
               {
                   Id = c.Id,
                   Summary = c.Summary,
                   Remarks = c.Remarks,
                   TemplateName = c.TemplateName,
                   CreatedAt = c.CreatedAt,
               }).OrderBy(c => c.CreatedAt).ToListAsync();
            var pagedData = GetPagedData(data, param.CurrentPage, param.PageSize);
            return pagedData;
        }
        public async Task<SelectTemplateResult> SelectTemplate(int Id)
        {
            var data = await _context.templates.Select(c => new SelectTemplateResult
            {
                Id = c.Id,
                Summary = c.Summary,
                Remarks = c.Remarks,
                TemplateName = c.TemplateName,
                CreatedAt = c.CreatedAt,
            }).FirstOrDefaultAsync(e => e.Id == Id);
            return data;
        }

        //客服聊天室
        public async Task<int> AddChatRoom(string Id)
        {
            var data = await _context.chatRooms.Select(c => c.Id).FirstOrDefaultAsync();
            if (data > 0) return 1;
            ChatRoom chatRoom = new ChatRoom()
            {
                ChatRoomId = Id,
                UserId = Id,
            };
            await _context.chatRooms.AddRangeAsync(chatRoom);
            int affectedRows = await _context.SaveChangesAsync();
            return affectedRows;
        }
        public async Task<object> SelectChatRoomList()
        {
            var data = await _context.chatRooms.Join(_context.users,
               c => c.UserId,
               u => u.Id,
               (c, u) => new
               {
                   Id = u.Id,
                   AvatarUrl = u.AvatarUrl,
                   Name = u.Name,

               }).OrderByDescending(c => c.Id).ToListAsync();
            return data;
        }
        public PagedResult<T> GetPagedData<T>(List<T> query, int pageNumber, int pageSize)
        {
            var result = new PagedResult<T>
            {
                CurrentPage = pageNumber,
                PageSize = pageSize,
                TotalCount = query.Count(),
                Items = query.Skip((pageNumber - 1) * pageSize).Take(pageSize).ToList()
            };

            return result;
        }
    }
}
